﻿using ICSharpCode.SharpZipLib.BZip2;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CustomizationMaintEntry
{
    public partial class frmCustomizationMaintEntry1023 : Form
    {
        public frmCustomizationMaintEntry1023()
        {
            InitializeComponent();
            this.ChkAll.Visible = false;
            this.Text += "    Data Base:" + DbHelperSQL.QueryDataSet("SELECT DB_NAME()").Tables[0].Rows[0][0].ToString();
            this.Text += "    Server Name:" + DbHelperSQL.QueryDataSet("SELECT SERVERPROPERTY('MachineName')").Tables[0].Rows[0][0].ToString();
            //this.pan_Pro.Visible = false;
        }

        private string DecompressString(string strChunk)
        {
            try
            {
                int intRead = 0;
                MemoryStream objMemStr = new MemoryStream(Convert.FromBase64String(strChunk));
                BZip2InputStream objBZip2Input = new BZip2InputStream(objMemStr);
                byte[] buffer = new byte[1000];
                MemoryStream objMemStrDec = new MemoryStream();
                while ((intRead = objBZip2Input.Read(buffer, 0, 1000)) > 0)
                {
                    objMemStrDec.Write(buffer, 0, intRead);
                }
                objBZip2Input.Close();
                objMemStr.Close();
                byte[] bytes = objMemStrDec.ToArray();
                objMemStrDec.Close();
                return Encoding.UTF8.GetString(bytes);
            }
            catch
            {
                return "Export Error";
            }
        }

        private void btnFind_Click(object sender, EventArgs e)
        {
            try
            {
                //10.2.3以前的客制存储在XXXChunk,之后存储在XXXDef
                this.dataGridView1.Columns.Clear();
                this.dataGridView1.DataSource = null;
                string strSql = "SELECT CAST(0 AS BIT) xz,XXXDef.Company,XXXDef.ProductID,XXXDef.TypeCode,XXXDef.Key1,XXXDef.Key2,XXXDef.Key3,XXXChunk.SeqNum,XXXDef.CGCCode,XXXDef.Description,XXXDef.LastUpdated,XXXDef.LastUpdatedBy,XXXDef.Version,XXXDef.SysCharacter04,XXXDef.SysCharacter05,XXXDef.DataBaseVersion,XXXDef.SysRowID,'' Result,XXXDef.CommentText  FROM Ice.XXXDef LEFT OUTER JOIN Ice.XXXChunk ON Ice.XXXDef.Company = Ice.XXXChunk.Company AND Ice.XXXDef.ProductID = Ice.XXXChunk.ProductID AND Ice.XXXDef.TypeCode = Ice.XXXChunk.TypeCode AND Ice.XXXDef.Key1 = Ice.XXXChunk.Key1 AND Ice.XXXDef.Key2 = Ice.XXXChunk.Key2 AND Ice.XXXDef.Key3 = Ice.XXXChunk.Key3 AND Ice.XXXDef.CGCCode = Ice.XXXChunk.CGCCode WHERE 1=1 ";
                if (txtName.Text.Trim() != "")
                    strSql += String.Format(" AND XXXDef.Key1 LIKE N'%{0}%'", txtName.Text.Trim());
                if (txtDesc.Text.Trim() != "")
                    strSql += String.Format(" AND XXXDef.Description LIKE N'%{0}%'", txtDesc.Text.Trim());
                strSql += " AND XXXDef.ProductID IN (''";
                if (chkEp.Checked == true)
                    strSql += String.Format(",'EP'");
                if (chkBe.Checked == true)
                    strSql += String.Format(",'BE'");
                strSql += " )";
                if (chkBe.Checked == false)
                {
                    strSql += " AND XXXDef.TypeCode IN ('Customization'";
                    if (chkWarn.Checked == true)
                        strSql += String.Format(",'CustomizationWarn'");
                    if (chkBack.Checked == true)
                        strSql += String.Format(",'CustomizationBack'");
                    strSql += " )";
                }
                DataTable objTable = new DataTable();
                objTable = DbHelperSQL.QueryDataSet(strSql).Tables[0];
                this.dataGridView1.DataSource = objTable;
                for (int intCol = 0; intCol <= this.dataGridView1.Columns.Count - 1; intCol++)
                {
                    //this.dataGridView1.Columns[intCol].SortMode = DataGridViewColumnSortMode.NotSortable;
                    this.dataGridView1.Columns[intCol].ReadOnly = this.dataGridView1.Columns[intCol].Name != "xz";
                }
                this.dataGridView1.Columns["xz"].Width = 30;
                this.dataGridView1.Columns["xz"].HeaderText = "";
                this.dataGridView1.Columns["Company"].Width = 60;
                this.dataGridView1.Columns["SysRowID"].Visible = false;
                this.dataGridView1.Columns["CommentText"].Visible = false;
                this.ChkAll.Visible = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        string strPath = "";
        private void btnExport_Click(object sender, EventArgs e)
        {
            //Thread myThread = new Thread(ExportCustom);
            //myThread.IsBackground = true;
            //myThread.Start(); //线程开始  
            ExportCustom();
        }
        //private delegate void ExportCustomDelegate();
        private void ExportCustom()
        {
            if (this.dataGridView1.DataSource == null) return;
            DataTable objTable = (DataTable)this.dataGridView1.DataSource;
            try
            {
                objTable.AcceptChanges();
                //objTable.DefaultView.RowFilter = "xz=1";
                if (objTable.DefaultView.Count <= 0)
                {
                    MessageBox.Show("至少选择一条记录进行打印!");
                    return;
                }
                if (strPath.Trim() == "")
                {
                    FolderBrowserDialog diaFB = new FolderBrowserDialog();
                    diaFB.Description = "请选择文件路径";
                    if (diaFB.ShowDialog() == DialogResult.OK)
                    {
                        strPath = diaFB.SelectedPath;
                    }
                    else
                    { return; }
                }
                //DataTable objTablePrint = objTable.DefaultView.ToTable();
                //objTable.DefaultView.RowFilter = "";
                this.progressBar1.Minimum = 0;
                this.progressBar1.Maximum = objTable.Select("xz=1").Length;
                this.progressBar1.Step = 1;
                this.progressBar1.Value = 0;
                foreach (DataRow row in objTable.Rows)
                {
                    if (Convert.ToBoolean(row["xz"]) == true)
                    {
                        string strChunk = (string)DbHelperSQL.ExecReadField(String.Format("SELECT Content Chunk FROM Ice.XXXDef WHERE SysRowID='{0}'", row["SysRowID"]), DbHelperSQL.strPubConnectionEpicor);
                        CustomizationDS nds = new CustomizationDS();
                        StringReader objSR = new StringReader(strChunk);
                        nds.ReadXml(objSR, XmlReadMode.IgnoreSchema);
                        objSR.Close();
                        objSR = null;
                        //string strChunkDec = DecompressString(strChunk);
                        //if (strChunkDec != string.Empty && strChunkDec != "Export Error")
                        //{
                        //    StringReader objSR = new StringReader(strChunkDec);
                        //    nds.ReadXml(objSR, XmlReadMode.IgnoreSchema);
                        //    objSR.Close();
                        //    objSR = null;
                        //}
                        if (!nds.ExtendedProperties.ContainsKey("Company"))
                        {
                            nds.ExtendedProperties.Add("Company", String.Format("{0}", row["Company"]));
                        }
                        else
                        {
                            nds.ExtendedProperties["Company"] = "";
                        }
                        if (!nds.ExtendedProperties.ContainsKey("ProductID"))
                        {
                            nds.ExtendedProperties.Add("ProductID", String.Format("{0}", row["ProductID"]));
                        }
                        else
                        {
                            nds.ExtendedProperties["ProductID"] = "";
                        }
                        if (!nds.ExtendedProperties.ContainsKey("TypeCode"))
                        {
                            nds.ExtendedProperties.Add("TypeCode", String.Format("{0}", row["TypeCode"]));
                        }
                        else
                        {
                            nds.ExtendedProperties["TypeCode"] = "";
                        }
                        if (!nds.ExtendedProperties.ContainsKey("CGCCode"))
                        {
                            nds.ExtendedProperties.Add("CGCCode", String.Format("{0}", row["CGCCode"]));
                        }
                        else
                        {
                            nds.ExtendedProperties["CGCCode"] = "";
                        }
                        if (!nds.ExtendedProperties.ContainsKey("Key1"))
                        {
                            nds.ExtendedProperties.Add("Key1", String.Format("{0}", row["Key1"]));
                        }
                        else
                        {
                            nds.ExtendedProperties["Key1"] = "";
                        }
                        if (!nds.ExtendedProperties.ContainsKey("Key2"))
                        {
                            nds.ExtendedProperties.Add("Key2", String.Format("{0}", row["Key2"]));
                        }
                        else
                        {
                            nds.ExtendedProperties["Key2"] = "";
                        }
                        if (!nds.ExtendedProperties.ContainsKey("Key3"))
                        {
                            nds.ExtendedProperties.Add("Key3", String.Format("{0}", row["Key3"]));
                        }
                        else
                        {
                            nds.ExtendedProperties["Key3"] = "";
                        }
                        if (!nds.ExtendedProperties.ContainsKey("Description"))
                        {
                            nds.ExtendedProperties.Add("Description", String.Format("{0}", row["Description"]));
                        }
                        else
                        {
                            nds.ExtendedProperties["Description"] = "";
                        }
                        if (!nds.ExtendedProperties.ContainsKey("CommentText"))
                        {
                            nds.ExtendedProperties.Add("CommentText", String.Format("{0}", row["CommentText"]));
                        }
                        else
                        {
                            nds.ExtendedProperties["CommentText"] = "";
                        }

                        string strFile = "";
                        strFile += row["Key2"] + "_" + row["TypeCode"] + "_" + row["Key1"] + (row["Description"].ToString().Trim() == "" ? "" : "(" + row["Description"] + ")") + "_" + "CustomExport" + "_" + ToDateTime(row["LastUpdated"]).ToString("yyyyMMdd") + "_" + row["LastUpdatedBy"] + "_" + row["SysCharacter04"];
                        strFile = strPath + @"\" + strFile + ".Xml";
                        nds.WriteXml(strFile, XmlWriteMode.WriteSchema);
                        if (this.progressBar1.InvokeRequired == true)
                        {
                            //ExportCustomDelegate objDelegate = ExportCustom;
                            //this.progressBar1.Invoke(objDelegate);
                        }
                        else
                        {
                            this.progressBar1.Value += 1;
                        }
                        Application.DoEvents();
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            { objTable.DefaultView.RowFilter = ""; }
        }

        private DateTime ToDateTime(object value)
        {
            DateTime dtValue;
            if (DateTime.TryParse(value.ToString(), out dtValue) == true)
            { return dtValue; }
            return dtValue;
        }

        private void ChkAll_CheckedChanged(object sender, EventArgs e)
        {
            foreach (DataGridViewRow row in this.dataGridView1.Rows)
            {
                row.Cells["xz"].Value = this.ChkAll.Checked;
            }
        }

        private void chkError_CheckedChanged(object sender, EventArgs e)
        {
            DataTable objTable = (DataTable)this.dataGridView1.DataSource;
            objTable.AcceptChanges();
            objTable.DefaultView.RowFilter = (chkError.Checked == true ? "Result<>''" : "");
        }

        private void btnSeach_Click(object sender, EventArgs e)
        {
            if (this.dataGridView1.DataSource == null) return;
            DataTable objTable = (DataTable)this.dataGridView1.DataSource;
            try
            {
                objTable.AcceptChanges();
                this.progressBar1.Minimum = 0;
                this.progressBar1.Maximum = objTable.Select("xz=1").Length;
                this.progressBar1.Step = 1;
                this.progressBar1.Value = 0;
                foreach (DataRow row in objTable.Rows)
                {
                    if (Convert.ToBoolean(row["xz"]) == true)
                    {
                        string strChunk = (string)DbHelperSQL.ExecReadField(String.Format("SELECT Content Chunk FROM Ice.XXXDef WHERE SysRowID='{0}'", row["SysRowID"]), DbHelperSQL.strPubConnectionEpicor);
                        CustomizationDS nds = new CustomizationDS();
                        //string strChunkDec = DecompressString(strChunk);
                        string[] strSplit = txtName.Text.Trim().Split(',');
                        for (int intRow = 0; intRow <= strSplit.Length - 1; intRow++)
                        {
                            if (strChunk.ToUpper().IndexOf(strSplit[intRow].ToString().Trim().ToUpper()) >= 0 && strSplit[intRow].ToString().Trim() != "")
                            {
                                if (row["Result"].ToString().Trim() == "" && intRow == 0)
                                    row["Result"] = "Ok";
                            }
                            else
                            {
                                row["Result"] = "";
                            }
                        }
                        row.AcceptChanges();
                        if (this.progressBar1.InvokeRequired == true)
                        {
                            //ExportCustomDelegate objDelegate = ExportCustom;
                            //this.progressBar1.Invoke(objDelegate);
                        }
                        else
                        {
                            this.progressBar1.Value += 1;
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            { objTable.DefaultView.RowFilter = ""; }
        }
    }
}
